package libs

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors(origins []string) gin.HandlerFunc {
	return func(context *gin.Context) {
		origin := context.Request.Header.Get("Origin")
		allowed := false

		// Check if the origin is allowed
		for _, o := range origins {
			if o == origin {
				allowed = true
				break
			}
		}

		// If the origin is allowed, set the headers
		if allowed {
			context.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
			context.Writer.Header().Set("Access-Control-Max-Age", "10000")
			context.Writer.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS")
			context.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization,Content-Type,Accept")
		}

		// Handle preflight requests
		if context.Request.Method == http.MethodOptions {
			context.AbortWithStatus(http.StatusNoContent)
			return
		}

		context.Next()
	}
}
